package org.ccvi.policy.web.userinfo;

import java.util.List;

import org.apache.struts2.convention.annotation.Result;
import org.apache.struts2.convention.annotation.Results;
import org.ccvi.policy.entity.userinfo.Resource;
import org.ccvi.policy.entity.userinfo.Role;
import org.ccvi.policy.service.userinfo.UserInfoManager;
import org.ccvi.policy.web.CrudActionSupport;
import org.springframework.beans.factory.annotation.Autowired;
import org.springside.modules.orm.hibernate.HibernateWebUtils;

/**
 * 角色管理Action.
 * 
 * 使用Struts2 convention-plugin annotation定义Action参数. 演示不分页的简单管理界面.
 * 
 * @author calvin
 */
@Results( { @Result(name = CrudActionSupport.RELOAD, location = "role.action", type = "redirect") })
public class PolicyRoleAction extends CrudActionSupport<Role>{

	private static final long serialVersionUID = 1476020607931033360L;

	@Autowired
	private UserInfoManager userinfoManager;

	// 页面属性 //
	private Long id;
	private Role entity;
	private List<Role> roleList;// 角色列表
	private List<Long> checkedResourceIds; // 页面中钩选的角色id列表

	// ModelDriven 与 Preparable函数 //
	public Role getModel() {
		return entity;
	}

	public void setId(Long id) {
		this.id = id;
	}

	@Override
	protected void prepareModel() throws Exception {
		if (id != null) {
			entity = userinfoManager.getRole(id);
		} else {
			entity = new Role();
		}
	}

	// CRUD Action 函数 //
	@Override
	public String list() throws Exception {
		roleList = userinfoManager.getAllRole();
		return SUCCESS;
	}

	@Override
	public String input() throws Exception {
		checkedResourceIds = entity.getResourceIds();
		return INPUT;
	}

	@Override
	public String save() throws Exception {
		HibernateWebUtils.mergeByCheckedIds(entity.getResources(),
				checkedResourceIds, Resource.class);
		userinfoManager.saveRole(entity);
		addActionMessage("保存角色成功");
		return RELOAD;
	}

	@Override
	public String delete() throws Exception {
		userinfoManager.deleteRole(id);
		addActionMessage("删除角色成功");
		return RELOAD;
	}

	// 页面属性访问函数 //
	public List<Role> getRoleList() {
		return roleList;
	}

	public List<Long> getCheckedResourceIds() {
		return checkedResourceIds;
	}

	public void setCheckedResourceIds(List<Long> checkedResourceIds) {
		this.checkedResourceIds = checkedResourceIds;
	}

	public List<Resource> getResourceList() {
		return userinfoManager.getAllResource();
	}
}
